//
//  AllProductsController.m
//  华康通
//
//  Created by leiyu on 16/4/29.
//  Copyright © 2016年 华康集团. All rights reserved.
//

#import "AllProductsController.h"
#import "FirstPageProductCell.h"
#import "ProductDetailViewController.h"
#import "JSONFromProduct.h"
#import "UMMobClick/MobClick.h"

@interface AllProductsController ()

//产品列表数量
@property (nonatomic, strong) NSMutableArray* products;
@property (nonatomic, strong) MJRefreshAutoGifFooter *footer;
@property (nonatomic, strong) MJRefreshGifHeader *header;
//用一个数来记录用户上拉加载的次数
@property (nonatomic, unsafe_unretained) NSInteger slCount;

@property (nonatomic, strong) ShowNoNetworkView* workView;

@end

@implementation AllProductsController

- (NSMutableArray*)products
{
    if (!_products)
    {
        _products = [NSMutableArray array];
    }
    return _products;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.slCount = 1;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    [self.tableView registerNib:[UINib nibWithNibName:@"FirstPageProductCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    //请求数据
    [self postPramaWithPageSize:1 withPages:20];
    self.header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = self.header;
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.footer = self.footer;
    [self.footer setHidden:YES];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.navigationController.navigationBar.hidden = NO;
    [MobClick beginLogPageView:@"MyTabBarController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"MyTabBarController"];
}

//下拉刷新
- (void)loadNewData
{
    NSLog(@"下拉刷新");
    self.slCount = 1;
    [self.products removeAllObjects];
    [self.tableView.header beginRefreshing];
    [self.tableView.footer resetNoMoreData];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postPramaWithPageSize:self.slCount withPages:20];
    });
}
//上拉加载
- (void)loadMoreData
{
    self.slCount++;
    NSLog(@"self.slCount = %ld",(long)self.slCount);
    NSLog(@"上拉加载");
//    [self.tableView.footer resetNoMoreData];
    [self postPramaWithPageSize:self.slCount withPages:20];
}
/**
 *  停止刷新
 */
-(void)endRefresh
{
    if ([self.tableView.header isRefreshing])
    {
        [self.tableView.header endRefreshing];
    }
    if ([self.tableView.footer isRefreshing])
    {
        [self.tableView.footer endRefreshing];
    }
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark  //获取产品列表

- (void)postPramaWithPageSize:(NSInteger)pageSize withPages:(NSInteger)pages
{
    //设置缓存的key
//    NSString* cacheStr;
//    if (self.product_detailtype_id)
//    {
//        cacheStr = [NSString stringWithFormat:@"getProductList_ALL_Type_%ld_%ld_%@",(long)pageSize,(long)pages,self.product_detailtype_id];
//    }
//    if (self.brand_id)
//    {
//        cacheStr = [NSString stringWithFormat:@"getProductList_ALL_Brand_%ld_%ld_%@",(long)pageSize,(long)pages,self.brand_id];
//    }
    NSDictionary* json;
    if (self.product_detailtype_id)
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"getProductList",
                 @"requestObject":@{@"recommendCode":@"",
                                    @"groupType":@"",
                                    @"brandId":@"",
                                    @"isSell":@"2",
                                    @"productDetailType":self.product_detailtype_id,
                                    @"pageParams":@{
                                            @"currentPage":[NSString stringWithFormat:@"%ld",(long)pageSize],
                                            @"pageSize":[NSString stringWithFormat:@"%ld",(long)pages],
                                            @"queryAll":@"false"}
                                    }
                 };
    }
    if (self.brand_id)
    {
        json = @{@"platformType":@"1",
                 @"orderType":@"01",
                 @"requestService":@"getProductList",
                 @"requestObject":@{@"recommendCode":@"",
                                    @"groupType":@"",
                                    @"brandId":self.brand_id,
                                    @"isSell":@"2",
                                    @"productDetailType":@"",
                                    @"pageParams":@{
                                            @"currentPage":[NSString stringWithFormat:@"%ld",(long)pageSize],
                                            @"pageSize":[NSString stringWithFormat:@"%ld",(long)pages],
                                            @"queryAll":@"false"}
                                    }
                 };
    }
    
    NSLog(@"json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self getProductsWithURL:url withParam:json];
}

//读取网络或本地的产品列表数据
- (void)readProductsListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"获取产品列表json = %@",json);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                [CacheData removeCacheWith:@"ISSHOWTGF_666"];
                for (NSDictionary* dict in json[@"responseObject"][@"productList"])
                {
                    JSONFromProduct* product = [JSONFromProduct productWithJSON:dict];
                    [self.products addObject:product];
                }
                if ([json[@"responseObject"][@"pageParams"] isKindOfClass:[NSDictionary class]] && json[@"responseObject"][@"pageParams"])
                {
                    //总条数
                    NSInteger i1 = [json[@"responseObject"][@"pageParams"][@"pageTotal"] integerValue];
                    //当前页
                    NSInteger i2 = [json[@"responseObject"][@"pageParams"][@"currentPage"] integerValue];
                    dispatch_async(dispatch_get_main_queue(), ^{

                        [self.footer setHidden:NO];

                        if (i1 == i2)
                        {
                            [self.tableView.footer noticeNoMoreData];
                        };
                        if ([json[@"responseObject"][@"productList"] count] == 0)
                        {
                            [self.tableView.footer noticeNoMoreData];
                        }
                    });
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.footer setHidden:YES];

                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.footer setHidden:YES];

                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.footer setHidden:YES];

            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefresh];
            if (self.products.count == 0)
            {
                [self createWorkView];
            }
            else
            {
                [self removeWorkView];
            }
            [self.tableView reloadData];
        });
    });
}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:self.view.bounds];
        self.workView.labelText = @"产品待开发中...";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowError;
        [self.workView createAllSubView];
        [self.view addSubview:self.workView];

    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;

}

- (void)getProductsWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:self.view.frame withVC:self];
    [networking showNetworkViewWithSuccess:^{
        
        self.tableView.scrollEnabled = YES;
        [self.header setHidden:NO];
        
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            //网络读取数据
            [self readProductsListWithData:responseObject];
        } failure:^(NSError *error) {
            //        [self endRefresh];
            NSLog(@"error.code = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.footer setHidden:YES];
                [self endRefresh];
                if (self.products.count == 0)
                {
                    [self createWorkView];
                }
                else
                {
                    [self removeWorkView];
                }
            });
        }];
        
    } failure:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableView.scrollEnabled = NO;
            [self.footer setHidden:YES];
            [self.header setHidden:YES];
            [self endRefresh];
        });
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
    
}


//立即投保
- (void)pushTBVC:(UIButton*)sender
{
    FirstPageProductCell *cell = (FirstPageProductCell *)[[sender superview]superview];
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    NSLog(@"indexPath.row = %ld",(long)indexPath.row);
    JSONFromProduct* product = self.products[indexPath.row];
    ProductDetailViewController* productDetailVC = [[ProductDetailViewController alloc]initWithNibName:@"ProductDetailViewController" bundle:nil];
    productDetailVC.isFirst = NO;
    productDetailVC.isPush = YES;
    productDetailVC.gotoUrl = product.gotoUrl;
    productDetailVC.productId = product.productCode;
    productDetailVC.isSell = product.isSell;
    productDetailVC.small_picture = product.small_picture;
    productDetailVC.product_features = product.product_features;
//    productDetailVC.title = product.productName;
    if (![product.gotoUrl isEqualToString:@""])
    {
        if ([TRUserAgenCode isLogin])
        {
            if ([productDetailVC.gotoUrl rangeOfString:@"{agentid}"].location != NSNotFound)
            {
                //替换agentid
                productDetailVC.gotoUrl = [productDetailVC.gotoUrl  stringByReplacingOccurrencesOfString:@"{agentid}" withString:[TRUserAgenCode getCustomerId]];
            }
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
        else
        {
            [self judeLoginWithMessage:@"您还没登录，请先登录!"];
        }
    }
    else
    {
        if ([TRUserAgenCode isLogin])
        {
//            productDetailVC.isPush = NO;
//            [self presentViewController:productDetailVC animated:YES completion:nil];
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
        else
        {
            [self judeLoginWithMessage:@"您还没登录，请先登录!"];
        }
//        productDetailVC.isPush = NO;
//        [self presentViewController:productDetailVC animated:YES completion:nil];
    }
}

//判断并且登录
- (void)judeLoginWithMessage:(NSString*)message
{
    ShowLogin(self.navigationController);
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.products count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FirstPageProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSLog(@"products = %@",_products);
    if (self.products.count > 0)
    {
        cell.TBButton.layer.cornerRadius = 17.0;
        cell.TBButton.layer.masksToBounds = YES;
        //    cell.titleLabel.adjustsFontSizeToFitWidth = YES;
        JSONFromProduct* product = self.products[indexPath.row];
        cell.titleLabel.text = product.productName;
        cell.detailTitleLabel.text = product.product_features;
        cell.priceLabel.text = [NSString stringWithFormat:@"%@%@",product.product_price,product.product_unit];
        cell.typeLabelImageView.image = LoadImage(@"nav");
        if ([product.product_price isEqualToString:@"无"])
        {
            [cell.priceLabel setHidden:YES];
        }
        else
        {
            [cell.priceLabel setHidden:NO];
        }
        if (![product.groupName isEqualToString:@""])
        {
            [cell.typeLabelImageView setHidden:NO];
            [cell.typeLabel setHidden:NO];
            cell.typeLabel.text = product.groupName;
            cell.typeLabel.adjustsFontSizeToFitWidth = YES;
        }
        else
        {
            [cell.typeLabelImageView setHidden:YES];
            [cell.typeLabel setHidden:YES];
            cell.typeLabel.adjustsFontSizeToFitWidth = YES;
        }
        if (![cell.titleLabel.text isEqualToString:@""])
        {
            cell.titleLabel.backgroundColor = FFFFFFColor;
            cell.detailTitleLabel.backgroundColor = FFFFFFColor;
            cell.otherLabel.backgroundColor = FFFFFFColor;
            cell.TBButton.backgroundColor = FFFFFFColor;
            cell.priceLabel.backgroundColor = FFFFFFColor;
            cell.TBButton.layer.borderColor = KMainColor.CGColor;
            cell.TBButton.layer.borderWidth = 1.0;
            if ([product.isSell isEqualToString:@"1"])
            {
                [cell.TBButton setTitle:@"立即投保" forState:UIControlStateNormal];
            }
            else
            {
                [cell.TBButton setTitle:@"查看详情" forState:UIControlStateNormal];
            }
            [cell.TBButton addTarget:self action:@selector(pushTBVC:) forControlEvents:UIControlEventTouchUpInside];
            
            if (![cell.priceLabel.text isEqualToString:@""])
            {
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:cell.priceLabel.text];
                NSInteger i = product.product_unit.length;
                if (![product.product_unit isEqualToString:@""])
                {
                    [str addAttribute:NSForegroundColorAttributeName value:SHOWCOLOR(@"858585") range:NSMakeRange(cell.priceLabel.text.length - i,i)];
                    [str addAttribute:NSFontAttributeName value:SetFont(12) range:NSMakeRange(cell.priceLabel.text.length - i,i)];
                    [str addAttribute:NSForegroundColorAttributeName value:KMainColor range:NSMakeRange(0,cell.priceLabel.text.length - i)];
                    [str addAttribute:NSFontAttributeName value:SetFont(20) range:NSMakeRange(0,cell.priceLabel.text.length - i)];
                }
                else
                {
                    [str addAttribute:NSForegroundColorAttributeName value:KMainColor range:NSMakeRange(0,cell.priceLabel.text.length)];
                    [str addAttribute:NSFontAttributeName value:SetFont(20) range:NSMakeRange(0,cell.priceLabel.text.length)];
                }
                cell.priceLabel.attributedText = str;
            }
            
            cell.otherLabel.layer.borderWidth = 1.0;
            cell.otherLabel.layer.borderColor = SHOWCOLOR(@"34B0FE").CGColor;
            [cell.typeLabelImageView setHidden:NO];
            [cell.typeLabel setHidden:NO];
            cell.typeLabel.text = product.groupName;
            cell.typeLabel.adjustsFontSizeToFitWidth = YES;
        }
        else
        {
            cell.titleLabel.backgroundColor = F1F1F1Color;
            cell.detailTextLabel.backgroundColor = F1F1F1Color;
            cell.otherLabel.backgroundColor = F1F1F1Color;
            cell.TBButton.backgroundColor = F1F1F1Color;
            cell.priceLabel.backgroundColor = F1F1F1Color;
            [cell.typeLabelImageView setHidden:YES];
            [cell.typeLabel setHidden:YES];
            [cell.TBButton setTitle:@"" forState:UIControlStateNormal];
        }
        if ([product.promotion_expenses isEqualToString:@" 无"] || [product.promotion_expenses isEqualToString:@""])
        {
            cell.otherLabel.text = @"";
            [cell.otherLabel setHidden:YES];
        }
        else
        {
            if ([TRUserAgenCode isLogin])
            {
                NSNumber* number = [CacheData getCache:@"ISSHOWTGF"];
                if (number != nil)
                {
                    if ([number boolValue])
                    {
                        cell.otherLabel.text = [NSString stringWithFormat:@"推广费用%@",product.promotion_expenses];
                        [cell.otherLabel setHidden:NO];
                    }
                    else
                    {
                        cell.otherLabel.text = @"";
                        [cell.otherLabel setHidden:YES];
                    }
                }
                else
                {
                    cell.otherLabel.text = [NSString stringWithFormat:@"推广费用%@",product.promotion_expenses];
                    [cell.otherLabel setHidden:NO];
                }
            }
            else
            {
                cell.otherLabel.text = @"";
                [cell.otherLabel setHidden:YES];
            }
            NSDictionary *attrs = @{NSFontAttributeName : SetFont(10.0)};
            CGSize size=[cell.otherLabel.text sizeWithAttributes:attrs];
            [cell.otherLabel setFrame:CGRectMake(127+8, 71, size.width + 3, 14)];
        }
        cell.productPhotoView.contentMode = UIViewContentModeScaleAspectFill;
        [cell.productPhotoView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE_URL,product.small_picture]]
                                 placeholderImage:LoadImage(@"loading_figure")];
        if ([product.small_picture rangeOfString:HTTP].location != NSNotFound)
        {
            [cell.productPhotoView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",product.small_picture]]
                                     placeholderImage:LoadImage(@"loading_figure")];
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSONFromProduct* product = self.products[indexPath.row];
    ProductDetailViewController* productDetailVC = [[ProductDetailViewController alloc]initWithNibName:@"ProductDetailViewController" bundle:nil];
    productDetailVC.isFirst = NO;
    productDetailVC.isPush = YES;
    productDetailVC.gotoUrl = product.gotoUrl;
    productDetailVC.productId = product.productCode;
    productDetailVC.isSell = product.isSell;
    productDetailVC.small_picture = product.small_picture;
    productDetailVC.product_features = product.product_features;
//    productDetailVC.title = product.productName;
    if (![product.gotoUrl isEqualToString:@""])
    {
        if ([TRUserAgenCode isLogin])
        {
            if ([productDetailVC.gotoUrl rangeOfString:@"{agentid}"].location != NSNotFound)
            {
                //替换agentid
                productDetailVC.gotoUrl = [productDetailVC.gotoUrl  stringByReplacingOccurrencesOfString:@"{agentid}" withString:[TRUserAgenCode getCustomerId]];
            }
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
        else
        {
            [self judeLoginWithMessage:@"您还没登录，请先登录!"];
        }
    }
    else
    {
        if ([TRUserAgenCode isLogin])
        {
//            productDetailVC.isPush = NO;
//            [self presentViewController:productDetailVC animated:YES completion:nil];
            [self.navigationController pushViewController:productDetailVC animated:YES];
        }
        else
        {
            [self judeLoginWithMessage:@"您还没登录，请先登录!"];
        }
    }
}


@end
